package com.hl.encrypt_descrypt;

import org.junit.Test;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.security.Key;
import java.security.KeyStore;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.Base64;

/**
 * @describe:
 */
public class ks {

    public static void main(String[] a) throws Exception {

        String keystoreName = "F:\\青岛中行\\trunk\\Documents\\D5.Others\\cert\\test.ks";
        String keystorePassword = "123456";
        String alias = "test";
        String keyPassword = "112233";

        KeyStore ks = KeyStore.getInstance("jks");
        ks.load(new FileInputStream(keystoreName), keystorePassword.toCharArray());
        Key key = ks.getKey(alias, keyPassword.toCharArray());
        Base64.Encoder encoder = Base64.getEncoder();
        String privatekey = encoder.encodeToString(key.getEncoded());

        System.out.println("-----BEGIN PRIVATE KEY-----");
        System.out.println(privatekey);
        System.out.println("-----END PRIVATE KEY-----");
    }


    /**
     * 从cer文件中获取公钥
     *
     * @throws Exception
     */
    @Test
    public void getCerInfo() throws Exception {
        File file = new File("F:\\青岛中行\\trunk\\Documents\\D5.Others\\cert\\test.cer");
        try (InputStream ins = new FileInputStream(file);) {
            //创建x.509工厂类
            CertificateFactory cf = CertificateFactory.getInstance("X.509");
            //创建证书实例
            X509Certificate oCer = (X509Certificate) cf.generateCertificate(ins);

            System.out.println("证书公钥信息" + oCer.getPublicKey());
            Base64.Encoder encoder = Base64.getEncoder();
            String publicKeyString = encoder.encodeToString(oCer.getPublicKey().getEncoded());
            System.out.println(publicKeyString);
        }
    }
}
